<template>
  <div id="LabTMLBDict">
    <Breadcrumb content="分管类别" />
    <div class="bodyContent">
      <!-- vxe-toolbar -->
      <Splitpanes class="area">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="form.keyvalue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup.enter.native="findList" @search-click="findList" @clear="findList"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-add" content="新增" @click="addBarCodeType"></vxe-button>
              <!-- <vxe-button
                type="text"
                class="button-blue"
                icon="vxe-icon-save"
                content="保存"
                @click="saveBarCodeType"
              ></vxe-button>-->
              <vxe-button type="text" class="button-red" icon="vxe-icon-delete" content="删除" @click="deleteBarCodeType"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :loading="showLoading" height="auto" :data="tableData" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, enabled: false }" @cell-click="tableCellClick" :menu-config="menuConfig" @menu-click="contextMenuClickEvent" show-overflow keep-source>
              <vxe-column type="checkbox" width="26"></vxe-column>
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="barcodeNo" title="编码" width="60">
                <template #edit="{ row }">
                  <vxe-input v-model="row.barcodeNo" clearable @clear="() => { }" @keyup.enter.native="() => { }" placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="barcodeNa" title="名称" min-width="120">
                <template #edit="{ row }">
                  <vxe-input v-model="row.barcodeNa" clearable @clear="() => { }" @keyup.enter.native="() => { }" placeholder="关键字查询"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="shortName" title="简称" width="90">
                <template #edit="{ row }">
                  <vxe-input v-model="row.shortName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="collectQty" title="采集量" align="right" width="60"></vxe-column>
              <vxe-column field="sampleTypeName" title="样本类型" align="center" width="90">
                <template #edit="{ row }">
                  <vxe-input v-model="row.sampleTypeName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="labelTips" title="标签提示文字" align="center" width="110">
                <template #edit="{ row }">
                  <vxe-input v-model="row.labelTips" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="labelPrintNum" title="打印份数" align="center" width="70">
                <template #edit="{ row }">
                  <vxe-input v-model="row.labelPrintNum" type="integer"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="color" title="颜色" width="100">
                <template #default="{ row }">
                  <el-tag class="margin-lr-xs" :style="{ background: row.color ? row.color : '' }" v-if="row.color">{{ row.color }}</el-tag>
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.color" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="colorText" title="颜色文本" width="70">
                <template #edit="{ row }">
                  <vxe-input v-model="row.colorText" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="feeCodeId" title="费用编码" width="70">
                <template #edit="{ row }">
                  <vxe-input v-model="row.feeCodeId" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="remark" title="备注" width="100">
                <template #edit="{ row }">
                  <vxe-input v-model="row.remark" type="text"></vxe-input>
                </template>
              </vxe-column>
              <!-- <vxe-column field="orgName" title="组织机构" min-width="150">
                <template #edit="{ row }">
                  <vxe-input v-model="row.orgName" type="text"></vxe-input>
                </template>
              </vxe-column> -->
            </vxe-table>
          </div>
        </Pane>

        <Pane size="40">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <LabBarCodeTypeForm ref="LabBarCodeTypeFormRef" :currentRow="currentRow" @findList="findList" />
              <!-- <Pane size="55">
                <el-tabs type="border-card" style="height:100%;">
                  <el-tab-pane label="分管类别样本类型对照">
                  </el-tab-pane>
                </el-tabs>
              </Pane>-->
            </el-tab-pane>
            <ExtraPropertyPanel :busRow="curSlectRow" />
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import LabBarCodeTypeForm from './LabBarCodeTypeForm.vue'; //基本信息表单组件
import ExtraPropertyPanel from '@/components/ExtraPropertyPanel.vue';
import { AppStore } from '@/stores/store';
import { DateToString, IsEmpty, sortByField } from '@/utils/common';
let store = AppStore();

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();

// 左侧表格:
let showLoading = ref(false); //刷新+表格加载
const form = reactive({ keyvalue: '', name: store.userInfo.orgName, orgId: store.userInfo.orgId }); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive([]); //表格数据
const curSlectRow = ref({});
// 右侧表单:
const LabBarCodeTypeFormRef = ref<InstanceType<typeof LabBarCodeTypeForm>>(); //基本信息表单标记ref
let currentRow: any = reactive({ id: '', code: '' }); //基本信息表单当前行数据
const EditExtraPropertiesRef = ref(null); //配置扩展属性弹框ref

// vxe-table 表格右击属性
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});
// 方法定义区 =============
onMounted(() => {
  findList(); // 获取分管类别表格数据
});
// 获取 分管类别表格数据
const findList = () => {
  showLoading.value = true;
  tableData.length = 0; //放入数据前清空数据
  const url = '/api/lab/labbarcodetype/findBarCodeTypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { keyWords: form.keyvalue, orgId: form.orgId } })
    .then(async (res: any) => {
      tableData.push(...sortByField(res.data, 'barcodeNo', 'asc'));
      showLoading.value = false;
      if (res && res.data && res.data.length > 0) {
        currentRow.id = '';
        tableCellClick({ row: res.data[0] });
        const $table = tableRef.value;
        if ($table) {
          await $table.setCurrentRow(res.data[0]);
        }
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('获取分管类别表格数据异常', VxeNotifyType.error);
    });
};

// 新增分管类别
async function addBarCodeType() {
  const $formRef = LabBarCodeTypeFormRef.value;
  LabBarCodeTypeFormRef.value?.addNew((e: any) => {
    //todo
  });
}

// 保存分管类别
function saveBarCodeType() {
  const $formRef = LabBarCodeTypeFormRef.value;
  LabBarCodeTypeFormRef.value?.saveForm((e: any) => {
    // findList();
  });
}

// 删除分管类别
async function deleteBarCodeType() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的分管类别', VxeNotifyType.info);
    return;
  } else if (arr.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/lab/labbarcodetype/deleteBarCodeType';
        const arr = await tableRef.value?.getCheckboxRecords(true);
        if (arr && arr.length > 0 && arr[0]) {
          proxy.$http
            .post(url, arr[0])
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除分管类别成功', VxeNotifyType.success);
                findList();
                LabBarCodeTypeFormRef.value?.clearFormData();
              } else {
                VxeMessage('删除分管类别失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除分管类别异常', VxeNotifyType.error);
            });
        }
      });
  }
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if ($table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        deleteBarCodeType();
        break;
      case 'save':
        saveBarCodeType();
        break;
    }
  }
};

// 表格选中当前行
function tableCellClick({ row }: any) {
  curSlectRow.value = row;
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}
</script>
<style lang="scss" scoped>
#LabTMLBDict {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .tableBox {
        height: calc(100% - 40px);

        .el-tag {
          color: $base-white;
        }
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 30px);

          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
